﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace FS_2013_GUI
{
    /// <summary>
    /// Логика взаимодействия для MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        public static AutoResetEvent ev;

        public MainWindow()
        {
            ev = new AutoResetEvent(false);
            InitializeComponent();
            SetDefaultSettings();
        }

        private void SetDefaultSettings()
        {
            Global.admin = false;
            Global.authorizedUser = false;
            Global.cn = new Connection();
            ClearText();
        }

        private void ClearText()
        {
            loginBox.Clear();
            passwordBox.Clear();
            ErrorLbl.Content = "";
        }

        private bool AuthorizeUser()
        {
            Global.cn.Start();
            while (!Global.cn.ready) { }
            Global.cn.Send("login " + loginBox.Text + " " + passwordBox.Password);
            ev.WaitOne();
            return Global.authorizedUser;
        }

        private void loginBtn_Click(object sender, RoutedEventArgs e)
        {
            ErrorLbl.Content = "";
            if (loginBox.Text == "" || passwordBox.Password == "")
            {
                ErrorLbl.Content = "Error!!! One of the fields can't be empty!!!";
            }
            else
            {
                if (AuthorizeUser())
                {
                    FSMain fsMainWind = new FSMain(loginBox.Text);
                    this.Hide();
                    fsMainWind.ShowDialog();
                    this.Show();
                }
                else
                {
                    ErrorLbl.Content = "Wrong login or password!!!";
                }
            }
            Global.cn.Send("disconnect");
            Thread.Sleep(500);
            Global.cn.Disconnect();
            SetDefaultSettings();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Environment.Exit(1);
        }
    }
}
